import type { request, response, nextFunc } from "../../interface/type";
import { verifyJwt } from "../../utils/jwt";
import { getErr } from "../middleware/getSendResult";
import { CODE } from "../../utils/const";

// 验证是否登录中间件，如果没有登录状态码403， code为-1
export const verifyIsLogin = async (req: request, res: response, next: nextFunc) => {
    let token = req.cookies.token;
    if (!token) {
        token = req.headers.authorization;
    }
    if (!token) {
        res.status(403).send(getErr("请先登录", CODE.needLogin));
    } else {
        try {
            let user = await verifyJwt(token);
            (req as any).user = user
            next();
        } catch (error) {
            res.status(403).send(getErr("登录信息失效，请重新登录", CODE.needLogin));
        }
    }
};
